package function;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


public class Dateutils {
    // 2021-01-01   2022-01-01
    public static List<String> getMonths(String startStr, String endStr) {
        List<String> list = new ArrayList<>();
        SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM");
        Calendar calendar = Calendar.getInstance(); // 月份+1
        try {
            //处理结束时间：
            String endtime = sdf2.format(sdf1.parse(endStr));// 2022-01-01 --> 2022-01
            Date date = sdf1.parse(startStr);// 日期对象 2021-01-01
            String str = sdf2.format(date);//2021-01
            while (true){
                list.add(str);
                calendar.setTime(date);
                calendar.add(Calendar.MONTH, 1);//月份+1  日期对象 2021-02-01
                date = calendar.getTime();
                str = sdf2.format(date);
                if (endtime.equals(str)){
                    list.add(str);
                    break;
                }
            }
            return list;
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws ParseException {

        List<String> list = getMonths("2021-01-01", "2022-01-01");

        System.out.println(list);

     /*   String str = "2021-01-01";
        SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf1.parse(str);  //2021-01-01

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH,1);

        Date time = calendar.getTime();
        SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM");
        String str2 = sdf2.format(time);*/
/*
        if (str2.equals(end)) {
            break;

        }*/




    }
}
